using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

namespace BlockOS.Client
{
    public class Draggable : MonoBehaviour, IDragHandler, IPointerDownHandler
    {
        private RectTransform rectTransform;

        private Vector2 m_DownPosition;
        private Vector2 m_DownAnchoredPosition;

        private void Awake()
        {
            rectTransform = GetComponent<RectTransform>();
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            m_DownPosition = eventData.position;
            m_DownAnchoredPosition = rectTransform.anchoredPosition;
        }

        public void OnDrag(PointerEventData eventData)
        {
            var delta = eventData.position - m_DownPosition;
            var targetPosition = m_DownAnchoredPosition + delta;
            var displayRectTransform = GameClient.Instance.WindowManager.rectTransform;
            var displayWidth = displayRectTransform.rect.width;
            var displayHeight = displayRectTransform.rect.height;

            Debug.Log($"{displayWidth},{displayHeight}");

            var halfWidth = rectTransform.rect.width;
            var halfHeight = rectTransform.rect.height;
            var horizontalBound = displayWidth - halfWidth;
            var verticalBound = displayHeight - halfHeight;

            targetPosition.x = Mathf.Clamp(targetPosition.x, -horizontalBound, horizontalBound);
            targetPosition.y = Mathf.Clamp(targetPosition.y, -verticalBound, verticalBound);

            rectTransform.anchoredPosition = targetPosition;
        }
    }
}
